package com.tanhua.server.service;

import com.aliyuncs.ram.model.v20150501.ListVirtualMFADevicesResponse;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import com.tanhua.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;
    @Autowired
    private  UserFreezeService userFreezeService;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private MqMessageService mqMessageService;
    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendCode(String phone) {
        User user = userApi.findByMobile(phone);
        if(user != null) {
            userFreezeService.checkUserStatus("1",user.getId());
        }
        String code = RandomStringUtils.randomNumeric(6);
        code = "123456";
        // smsTemplate.sendSms(phone, code);
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }

    public Map loginVerification(String mobile, String code) {
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + mobile);
        if(StringUtils.isEmpty(code) || !code.equals(redisCode)) {
            throw new RuntimeException("验证码校验失败");
        }
        redisTemplate.delete("CHECK_CODE_" + mobile);
        boolean isNew = false;
        User user = userApi.findByMobile(mobile);
        String type = "0101";
        if (user == null) {
            type = "0102";
            user = new User();
            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
            String hxUser = "hx"+user.getId();
             Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if(create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        mqMessageService.sendLogMessage(user.getId(),type,"user",null);

        Map<String, Object> tokenMap = new HashMap<String, Object>();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", mobile);
        String token = JwtUtils.getToken(tokenMap);
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("isNew", isNew);
        return result;
    }

    public boolean checkVerificationCode(String verificationCode) {
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + UserHolder.getMobile());
       boolean verification =true;
        if(StringUtils.isEmpty(verificationCode) || !verificationCode.equals(redisCode)) {
            verification =false;
        }
        redisTemplate.delete("CHECK_CODE_" + UserHolder.getMobile());

        return verification;
    }

    public void updataphone(String phone) {
        Long userId = UserHolder.getUserId();
        User user = new User();
        user.setId(userId);
        user.setMobile(phone);
        userApi.updatabyId(user);
    }
}